
/**
 * Copyright phonemap.com
 *
 * Licensed under the phonemap.com License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.phonemap.com/licenses/LICENSE-1.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var oldPos = null;
var waitingPos = null;
var curPos = null;

var timezone = 7;
var ROTATED_DEGREE = 90;
var R = 0.100;
var isOnline = true;
var MAX_DIST = 0.01;
var index = 0;

/**
 * Do geolocation.
 */

function getlocation() {
	if (navigator.geolocation) {
		
		navigator.geolocation
				.getCurrentPosition(positionSuccess, positionError);
	} else {
		positionError(-1);
	}
}

/**
 * Position error.
 * @param err
 */
function positionError(err) {
	var msg = "";
	switch (err.code) {
		case err.UNKNOWN_ERROR:
			msg = "Unable to find your location";
			break;
		case err.PERMISSION_DENINED:
			msg = "Permission denied in finding your location";
			break;
		case err.POSITION_UNAVAILABLE:
			msg = "Your location is currently unknown";
			break;
		case err.BREAK:
			msg = "Attempt to find location took too long";
			break;
		default:
			msg = "You need to enable location on browser to continue...";
	}
	document.getElementById('status').innerHTML = msg;
	console.log(msg);
}

/**
 * Position Success.
 * @param position
 */
function positionSuccess(position) {
	// Center the map on the new location
	var coords = position.coords || position.coordinate || position;
	curPos = LatLon(coords.latitude, coords.longitude);
	waitingPos = curPos;
	var located_time = calculateTime(timezone);
	var key = 'p' + index;
	var value = waitingPos.lat + ',' + waitingPos.lon + ',' + located_time;
	localStorage.setItem(key, value);
	index++;
//	var newNode = document.getElementById("map-canvas");      
//	newNode.innerHTML = newNode.innerHTML + '#' + value;
	$("#content").append("<li>" + key + "=" + value + "</li>");
//	if (oldPos != null) {
//		var dist = oldPos.distanceTo(curPos);
//		
//		if (dist > MAX_DIST) {
//			
//			if (oldPos != null && waitingPos != null && curPos != null) {
//				
//				if (IsSelected(waitingPos, oldPos, curPos)) {
//					//Put into list
//					if (isOnline) {
//						updatePosition(waitingPos);
//					} else {
//						//Put into browser storage
//						var located_time = calculateTime(timezone);
//						var key = 'p' + index;
//						var value = waitingPos.lat + ',' + waitingPos.lon + ',' + located_time;
//						localStorage.setItem(key, value);
//						index++;
//					}
//					
//					oldPos = waitingPos;
//					waitingPos = curPos;
//					curPos = null;
//					
//				} else {
//					waitingPos = curPos;
//					curPos = null;
//				}
//			} else {
//				to3Point(pos);
//			}
//		}
//	} else {
//		oldPos = LatLon(coords.latitude, coords.longitude);
//	}
}

function to3Point(pos) {
	if (oldPos == null) {
		oldPos = LatLon(pos.lat(), pos.lng());
	} else if (waitingPos == null) {
		waitingPos = LatLon(pos.lat(), pos.lng());
	} else {
		curPos = LatLon(pos.lat(), pos.lng());
	}
}

/**
 * Updates Position.
 * @param user
 */
function updatePosition(curpos) {
	console.log('Updating user into system...');
	//load user account from cookie
	var userId = $.cookie('useraccount');
	if (userId != '' && userId != null) {
		
		var located_time = calculateTime(timezone);
		var urlString = '&id=' + userId + '&latitude='
				+ curpos.lat() + '&longitude=' + curpos.lng() + '&located_time='
				+ located_time;
		$.ajax({
			url : "/user?action=updateposition"+urlString,
			type : "POST",
			data: userId,
			success : function(data) {
				console.log('Successfully updated ' + curpos.toString());
				//oldPos = curpos;
			},
			error : function(resp) {
				console.log('UnSuccessfully updated ' + curpos.toString());
				isOnline = false;
			}
		});
	} 

}

/**
 * Is Middle
 * @param value
 * @param num1
 * @param num2
 * @returns {Boolean}
 */
function isInside(value, num1, num2) {
	if (num1 < num2) {
		if (value > num1 && value < num2) {
			return true;
		}
	} else {
		if (value <= num1 && value >= num2) {
			return true;
		}
	}
	return false;
}

function IsSelected(mid, start, end) {
	var bearing = start.bearingTo(end);
	
	var pRight = start.destinationPoint(bearing + ROTATED_DEGREE, R);
	var pLeft = start.destinationPoint(bearing - ROTATED_DEGREE, R);
	
	var dist = start.distanceTo(mid);
	
	pRight = pRight.destinationPoint(bearing, dist);
	pLeft = pLeft.destinationPoint(bearing, dist);
	
	return !(isInside(mid.lat, pLeft.lat, pRight.lat) &&
			isInside(mid.lon, pLeft.lon, pRight.lon));
}

function initialize() {
//	var latlng = new google.maps.LatLng(-25.363882, 131.044922);
//	var myOptions = {
//		zoom : 4,
//		center : latlng,
//		mapTypeId : google.maps.MapTypeId.TERRAIN,
//		disableDefaultUI : true
//	}
//	map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
	//prepareGeolocation();
	//doGeolocation();
//	var idx = 0;
//	
//	var key = 'p' + idx;
//	var value = localStorage.getItem(key);
//	var stringValue = "";
//	while (value != null && value != 'undefined') {
//		stringValue += value;
//		idx++;
//		key = 'p' + idx;
//		value = localStorage.getItem(key);
//	}
//	getlocation();
	//$('#map-canvas').html('test1111111111111111111111111111111');
}

var listener = setInterval(function(){getlocation()},5000);
